package com.xhwl.centiotdata.handler.org.impl;

import com.xhwl.centiotdata.handler.account.impl.AccountDaHuaIccHandler;
import com.xhwl.centiotdata.handler.org.OrgFactory;
import com.xhwl.centiotdata.handler.org.OrgHandler;
import com.xhwl.centiotdata.pojo.dto.pedestrian.PedestrianIntegrationConfigDTO;
import com.xhwl.centiotdata.service.IOrgInfoService;
import com.xhwl.centiotdata.service.cent.IProjectCentService;
import com.xhwl.centiotdata.suppliersystem.dahuaIcc.OrgDaHuaIccHandler;
import com.xhwl.common.enums.OrganizationTypeEnum;
import com.xhwl.common.enums.ProductEnum;
import com.xhwl.common.pojo.cent.iot.OrgInfo;
import com.xhwl.common.pojo.cent.sdata.Organization;
import com.xhwl.common.query.cent.sdata.OrganizationQuery;
import com.xhwl.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

/**
 * 大华组织同步
 *
 * @author lixiaoyan
 * @description
 * @date 2023/2/7 16:05
 */
@Service
@Slf4j
public class OrgIntegrationDaHuaIccHandler extends OrgHandler {


    @Autowired
    private OrgDaHuaIccHandler orgDaHuaIccHandler;

    @Resource
    private IOrgInfoService iOrgInfoService;

    @Autowired
    IProjectCentService iProjectCentService;

    @Autowired
    private AccountDaHuaIccHandler accountDaHuaIccHandler;

    @Override
    public void createOrg(PedestrianIntegrationConfigDTO config, List<Organization> organizations) {
        log.info("==组织数据同步大华icc");
        HashMap<Integer, String> parent = new HashMap<>();
        //查询大华组织关联记录
        List<OrgInfo> orgInfoList = iOrgInfoService.getList(config.getProductId(), null);
        Integer enterpriseId = organizations.get(0).getEnterpriseId();
        Short industryId = organizations.get(0).getIndustryId();
        //查询企业（组织根节点）
        OrganizationQuery query = new OrganizationQuery();
        query.setEnterpriseId(enterpriseId);
        query.setTypes(Arrays.asList(OrganizationTypeEnum.ENTERPRISE.getId().intValue()));
        List<Organization> organizationListMap = iProjectCentService.organizationList(query);
        parent.put(organizationListMap.get(0).getParentId(), "1");
        //企业组织节点第三方记录处理
        OrgInfo result = orgInfoList.stream().filter(s -> s.getId().equals(organizationListMap.get(0).getId())).findAny().orElse(null);
        if (null != result && StringUtils.isNotEmpty(result.getOrgIndexCode())) {
            parent.put(organizationListMap.get(0).getId(), result.getOrgIndexCode());
        } else {
            OrgInfo orgInfo = syncOrg(organizationListMap.get(0), config, parent);
            parent.put(organizationListMap.get(0).getId(), orgInfo.getOrgIndexCode());
            iOrgInfoService.save(orgInfo);
        }
        //组织数据处理
        query.setTypes(Arrays.asList(OrganizationTypeEnum.ORG.getId().intValue()));
        List<Organization> organizationAreaList = iProjectCentService.organizationList(query);
        if (!CollectionUtils.isEmpty(organizationAreaList)) {
            List<OrgInfo> tmpList = new ArrayList<>();
            organizationAreaList.forEach(org -> {
                OrgInfo tmpOrg = orgInfoList.stream().filter(s -> s.getId().equals(org.getId())).findAny().orElse(null);
                if (null != tmpOrg && StringUtils.isNotEmpty(tmpOrg.getOrgIndexCode())) {
                    parent.put(org.getId(), tmpOrg.getOrgIndexCode());
                } else {
                    OrgInfo orgInfoTemp = syncOrg(org, config, parent);
                    if (orgInfoTemp != null) {
                        tmpList.add(orgInfoTemp);
                        parent.put(org.getId(), orgInfoTemp.getOrgIndexCode());
                    }
                }
            });
            iOrgInfoService.saveBatch(tmpList);
        }
    }

    private OrgInfo syncOrg(Organization org, PedestrianIntegrationConfigDTO config, HashMap<Integer, String> parent) {
        if (StringUtils.isNotEmpty(parent.getOrDefault(org.getParentId(), ""))) {
            Organization organization = new Organization();
            organization.setName(org.getName());
            organization.setParentId(Integer.parseInt(parent.get(org.getParentId())));
            String orgId = orgDaHuaIccHandler.addOrg(config, organization);
            if (StringUtils.isNotEmpty(orgId)) {
                OrgInfo orgInfo = new OrgInfo();
                orgInfo.setId(org.getId());
                orgInfo.setParentId(org.getParentId());
                orgInfo.setProductId(config.getProductId());
                orgInfo.setOrgName(org.getName());
                orgInfo.setOrgIndexCode(orgId);//存储大华icc部门id
                return orgInfo;
            }
        }
        return null;
    }

    @Override
    public void updateOrg(PedestrianIntegrationConfigDTO config, List<Organization> organizations) {
        organizations.forEach(org -> {
            // 如果创建的组织是ORG才能同步到大华
            if (org.getType() == OrganizationTypeEnum.ORG.getId().intValue()) {
                OrgInfo result = iOrgInfoService.getOrgInfo(org.getId(), config.getProductId());
                OrgInfo parent = iOrgInfoService.getOrgInfo(org.getParentId(), config.getProductId());
                if (null != result && StringUtils.isNotEmpty(result.getOrgIndexCode())) {
                    Organization organization = new Organization();
                    organization.setName(org.getName());
                    organization.setParentId(parent != null ? Integer.parseInt(parent.getOrgIndexCode()) : null);
                    organization.setId(Integer.parseInt(result.getOrgIndexCode()));
                    orgDaHuaIccHandler.updateOrg(config, organization);
                    result.setOrgName(org.getName());
                    iOrgInfoService.updateOrgInfo(result);
                }
            }
        });
    }

    @Override
    public void deleteOrg(PedestrianIntegrationConfigDTO config, List<Organization> organizations) {
        organizations.forEach(org -> {
            // 如果创建的组织是ORG才能同步到大华
            if (org.getType() == OrganizationTypeEnum.ORG.getId().intValue()) {
                OrgInfo result = iOrgInfoService.getOrgInfo(org.getId(), config.getProductId());
                if (null != result && StringUtils.isNotEmpty(result.getOrgIndexCode())) {
                    orgDaHuaIccHandler.deleteOrg(config, result);
                    iOrgInfoService.deleteOrgInfo(result.getId(), config.getProductId());
                }
            }
        });
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        OrgFactory.register(ProductEnum.DAHUA_ICC.id, this);
    }


}
